<?php
/**
 * common repository file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/04
 * Time: 17:52
 */
 
 namespace HiCommon\Repository;

use HiCommon\Model\OrderCheckpoint;

class OrderCheckpointRepository extends BaseRepository
{
    public function base_model(){
        return new \HiCommon\Model\OrderCheckpoint();
    }

    public function get_one_for_apply_refund($n_id){
        $arr_option = [
          'with'=>['apply_vehicle'],
          'field'=>['id','appointment_date','order_sn','pay_state','refund_state','appointment_state','complete_state','appraise_state']
        ];
        $res = self::base_find_one($n_id,$arr_option);
        return $res;

    }

    /*检测机构商户-年检预约单-接单数*/
    public function njyy_waiting_order_num_for_shop($n_shop_id){
        $arr_where['shop_id'] = $n_shop_id;
        $arr_where['pay_state'] = 2;
        $arr_where['appointment_state'] = 2;
        $arr_where['complete_state'] = -1;
        $result = self::get_count_by_where($arr_where);
        return $result;
    }

    /**
     * 分页获取全部数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all($arr_option = [])
    {
        return OrderCheckpoint::commonget($arr_option);
    }

    /**
     * 分页获取全部数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all_wherein(array $ids ,  array $arr_option = [])
    {
        return OrderCheckpoint::whereIn('shop_id' , $ids )->commonget($arr_option);
    }




    /**
     * 分页获取数据
     *
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($arr_option = [] , array $arr_search = [] )
    {
        return OrderCheckpoint::where(
            function ($query)
            use($arr_search) {
                $s_key_word = str_trim($arr_search['key_word']);
                $s_search_type = str_trim($arr_search['search_type']);
                if(mb_strlen($s_key_word) > 0){
                    if($s_search_type == 'plate_no'){
                        $query->where(
                          function($query)
                          use($s_key_word) {
                              $query->whereHas('check_vehicle',
                                function ($query)
                                use($s_key_word){
                                    $query->where('plate_no', 'like', '%'.$s_key_word.'%');
                                });
                          }
                        );

                    }
                    else{
                        $query->where('order_sn','like','%'.$s_key_word.'%');
                    }
                }



            })->commonpage($arr_option);
    }


    /**
     *  统计用户的订单信息
     *  hinq 2019 10 25
     *
     **/
    public function get_user_to_order_count( array $arr_where ){

        $raw = \DB::raw("count('*') as total, sum('pay_price') as pay_price , user_id ");
        return OrderCheckpoint::select($raw)->where( $arr_where )->with('user')->groupBy('user_id')->get();
    }


    /**
     * 按用户统计数据（商户端用户列表专属）
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_user_list( array  $arr_where ,  array $user_ids = []  ,array $arr_search = [] )
    {
        $iswhen = true;
        if( empty( $arr_search ) ){
            $iswhen = false;
        }
        $raw = \DB::raw("count('*') as total, SUM(price) as pay_price , user_id ");
        return OrderCheckpoint::select($raw)->where( $arr_where )->where(
            function ($query)
                use($user_ids) {
                if( count( $user_ids ) > 0  && $user_ids['key_word'] ){
                    $query->whereIn('user_id', $user_ids);
                }
        })->when($iswhen,
            function ($query)
            use($arr_search) {
                if( empty( $arr_search['act'] ) ){
                    $act = '';
                }else{
                    $act = $arr_search['act'] == 1 ? 'asc' : 'desc';   //金额排序 1：小到大   2：大到小
                }
                if( empty( $arr_search['act_num'] ) ){
                    $act_num = '';
                }else{
                    $act_num = $arr_search['act_num'] == 1 ? 'asc' : 'desc';   //金额排序 1：小到大   2：大到小
                }
                if( !empty( $act ) ){
                    $query->orderBy('pay_price',$act);
                }
                if( !empty( $act_num ) ){
                    $query->orderBy('total',$act_num);
                }
            })->with('user')->groupBy('user_id')->paginate(15);
    }

    /**
     *  根据商铺分组获取数据
     *
     **/
    public function get_shop_list(array $arr_where )
    {
        $raw = \DB::raw(" shop_id ");
        return OrderCheckpoint::select($raw)->where($arr_where)->with('shop')->groupBy('shop_id')->get();
    }


    
    /**
     * 通过where分页获取数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list_by_where($arr_where,$arr_option = [],$arr_search = [])
    {
        return OrderCheckpoint::where($arr_where)
                              ->where(
                                function($query)
                                use($arr_search) {
                                    $n_is_call_helpdriving = intval($arr_search['is_call_helpdriving']);
                                    if ( $n_is_call_helpdriving > 0) {
                                        $query->whereHas('check_vehicle',
                                          function ($query)
                                          use($n_is_call_helpdriving){
                                              $query->where('is_call_helpdriving', $n_is_call_helpdriving);
                                          });

                                    }
                                }
                              )
                              ->where(
                                function($query)
                                use($arr_search) {
                                    $n_check_state = intval($arr_search['check_state']);
                                    if ( $n_check_state > 0) {
                                        $query->whereHas('check_vehicle',
                                          function ($query)
                                          use($n_check_state){
                                              $query->where('check_state', $n_check_state);
                                          });

                                    }

                                }
                              )
                              ->where(
                                function($query)
                                use($arr_search) {
                                    $n_user_id = intval($arr_search['user_id']);
                                    if ( $n_user_id > 0) {
                                        $query->where('user_id', $n_user_id);
                                    }
                                }
                              )
                              ->where(
                                function($query)
                                use($arr_search) {
                                    $n_main_type = intval($arr_search['main_type']);
                                    if ( $n_main_type > 0) {
                                        $query->where('main_type', $n_main_type);
                                    }
                                }
                              )
                              ->where(
                                function ($query)
                                use($arr_search) {
                                    $s_date = str_trim($arr_search['appointment_date']);
                                    if(!empty($s_date)){
                                        $query->where('appointment_date', $s_date);
                                    }
                                })
                              ->commonpage($arr_option);

    }

    /**
     * 根据条件统计数量
     *
     * @param array $arr_where
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_count_by_where($arr_where)
    {
        return OrderCheckpoint::where($arr_where)->count();
    }

    /**
     * 根据条件统计数量
     *
     * @param array $arr_where
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_count_by_whereIn($arr_where)
    {
        return OrderCheckpoint::where($arr_where)->whereIn('complete_state',[1,2])->count();
    }

    public function get_appointing_count_by_where($arr_where){
//        $arr_where['appointment_state'] = 1;
        $arr_where['user_delete'] = 2;
        $arr_wherein = ['appointment_state'=>[1,2]];
        return OrderCheckpoint::basicWhereIn($arr_wherein)->where($arr_where)->count();

    }


    /**
     * 根据条件统计总和
     *
     * @param array  $arr_where
     * @param string $s_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_sum_by_where($arr_where = [],$s_field = 'mark')
    {
        return OrderCheckpoint::where($arr_where)->sum($s_field);
    }
    
    /**
     * 根据条件批量删除信息
     *
     * @param array $arr_where
     * @param bool  $method
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_by_where($arr_where = [],$method = false)
    {
        return OrderCheckpoint::where($arr_where)
                                    ->commondelete($method);
    }
    
    /**
     * 通过where获取一条数据
     *
     * @param array $arr_where
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one_by_where($arr_where,$arr_option = [])
    {
        return OrderCheckpoint::where($arr_where)->commonfirst($arr_option);
    }

    /**
     * 添加一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_one($arr_input)
    {
        return OrderCheckpoint::create($arr_input);
    }
    
    /**
     * 添加多条数据
     *
     * @param array $arr_data
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function add_many($arr_data)
    {
        return OrderCheckpoint::insert($arr_data);
    }

    /**
     * 查询一条数据
     *
     * @param int $n_id
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one(int $n_id, $arr_option = [])
    {
        return OrderCheckpoint::commonfind($n_id, $arr_option);
    }
    
    /**
     * 更新或新建一条数据
     *
     * @param $arr_where
     * @param $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_or_create($arr_where,$arr_input){
        $res = OrderCheckpoint::where($arr_where)->first();
        if(is_null($res)){
            OrderCheckpoint::create(array_merge($arr_where,$arr_input));
        }
        else{
            OrderCheckpoint::where($arr_where)->update($arr_input);
        }
        return OrderCheckpoint::where($arr_where)->first();
    }



    /**
     * 根据where更新数据
     *
     * @param $arr_where
     * @param $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_by_wherein($arr_ids = [],$s_field = 'id'){
        return OrderCheckpoint::whereIn($s_field,$arr_ids)->update($arr_input);
    }


    /**
     * 根据条件更新数据
     */
    public function edit_one_whereIn(array $map, array $arr_input)
    {
        return OrderCheckpoint::whereIn($map['key'] , $map['value'])->update($arr_input);
    }




    /**
     * 根据where更新数据
     *
     * @param $arr_where
     * @param $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_by_where($arr_where,$arr_input){
        return OrderCheckpoint::where($arr_where)->update($arr_input);
    }

    /**
     * 修改一条数据
     *
     * @param array $arr_input
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function edit_one(array $arr_input)
    {
        return OrderCheckpoint::where('id',$arr_input['id'])->update($arr_input);
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one(int $n_id)
    {
        return OrderCheckpoint::where('id', $n_id)
                             ->commondelete();
    }

    /**
     * 修改一条数据状态
     *
     * @param int    $n_id
     * @param int    $n_state
     * @param string $s_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function change_one_state(int $n_id,int $n_state,$s_field = 'state')
    {
        return OrderCheckpoint::where('id',$n_id)->update([$s_field=>$n_state]);

    }

    /**
     * 修改一条数据状态
     *
     * @param string    $s_order_sn
     * @param int    $n_state
     * @param string $s_field
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function change_one_state_by_ordersn(string $s_order_sn,int $n_state,$s_field = 'state')
    {
        return OrderCheckpoint::where('order_sn',$s_order_sn)->update([$s_field=>$n_state]);

    }
    
    /**
     * 字段自增
     *
     * @param int    $n_id
     * @param string $s_field
     * @param int    $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function increase_num($n_id,$s_field = 'commend_num',$n_step = 1)
    {
        return OrderCheckpoint::where('id',$n_id)->increment($s_field,$n_step);
    }

    /**
     * 字段自减
     *
     * @param int    $n_id
     * @param string $s_field
     * @param int    $n_step
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function decrease_num($n_id,$s_field = 'commend_num',$n_step = 1)
    {
        return OrderCheckpoint::where('id',$n_id)->decrement($s_field,$n_step);
    }







    /**
     * 分页获取数据-用户年检预约单列表
     *
     * @param array $arr_search
     * @param array $arr_where
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_get_list_by_search($arr_search,$arr_option)
    {
        $arr_remain_key = ['main_type','pay_state','refund_state','appointment_state','check_state','appraise_state'];
        $arr_remain = array_remain($arr_search,$arr_remain_key);
        return OrderCheckpoint::where($arr_remain)->apipage($arr_option);
    }

    /**
     * 查询一条数据详情
     *
     * @param int $n_id
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_user_get_detail(int $n_id, $arr_option = [])
    {
        $arr_option = [
          'with'=>[
            'shop',
            'user_company',
//            'user',
            'shop_checkpoint_apprise',
//            'wechat_refund',
//            'check_vehicle.wechat_refund',
            'check_vehicle.helpdriving',
            'check_vehicle.user_vehicle',
          ]
        ];

        return OrderCheckpoint::with($arr_option['with'])->select(['*'])->find($n_id);
    }

    /**
     * 查询一条数据详情
     *
     * @param int $n_id
     * @param array $arr_option
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_get_detail(int $n_id, $arr_option = [])
    {
        $arr_option = [
          'with'=>['shop','user_company','user','check_vehicle.user_vehicle','check_vehicle.refund_success','check_vehicle.helpdriving']
        ];
//        $arr_option = [
//          'with'=>['shop','user_company','user','shop_checkpoint_apprise','wechat_refund','check_vehicle.wechat_refund','check_vehicle.helpdriving']
//        ];

        return OrderCheckpoint::with($arr_option['with'])->select(['*'])->find($n_id);
    }

    /**
     * 通过条件查询所有数据
     */
    public function get_all_by_where($map, $option = [])
    {
        return OrderCheckpoint::where($map)->get($option)->toArray();
    }



    /**
     * 分页获取所有预约订单
     *
     * @param array $arr_option
     * @param array $arr_search
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function order_all_list($arr_option = [] , array $arr_search = [] )
    {
        return OrderCheckpointRepository::get_list($arr_option,$arr_search);
    }

    /**
     * 分页获取店铺所有预约订单
     *
     * @param int   $n_shop_id
     * @param array $arr_option
     * @param array $arr_search
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function shop_order_all_list($n_shop_id = 0,$arr_option = [] , array $arr_search = [] )
    {
        $arr_option['where']['shop_id'] = $n_shop_id;
        $result = OrderCheckpointRepository::get_list($arr_option,$arr_search);

        return $result;

    }

    /**
     * 分页获取店铺待处理预约订单
     *
     * @param int   $n_shop_id
     * @param array $arr_option
     * @param array $arr_search
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function shop_order_waiting_list($n_shop_id = 0,$arr_option = [] , array $arr_search = [] )
    {
        $arr_option['where']['shop_id'] = $n_shop_id;
        $arr_option['where']['appointment_state'] = 2;
        $arr_option['where']['pay_state'] = 2;
        $arr_option['where']['complete_state'] = -1;
//        $arr_option['where']['appraise_state'] = 0;
        return OrderCheckpoint::where(
          function ($query)
          use($arr_search) {
              if(!empty($arr_search['order_sn'])){
                  $query->where('order_sn','like','%'.$arr_search['order_sn'].'%');
              }

          })
//                              ->whereIn('refund_state',[0,2])
//                              ->whereIn('appraise_state',[1,2])
                              ->commonpage($arr_option);
    }

    /**
     * 分页获取店铺已完成预约订单
     *
     * @param int   $n_shop_id
     * @param array $arr_option
     * @param array $arr_search
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function shop_order_complete_list($n_shop_id = 0,$arr_option = [] , array $arr_search = [] )
    {
        $arr_option['where']['shop_id'] = $n_shop_id;
//        $arr_option['where']['appointment_state'] = 2;
//        $arr_option['where']['pay_state'] = 2;
//        $arr_option['where']['check_state'] = 2;
        //        $arr_option['where']['appraise_state'] = 0;
        return OrderCheckpoint::where(
          function ($query)
          use($arr_search) {
              if(!empty($arr_search['order_sn'])){
                  $query->where('order_sn','like','%'.$arr_search['order_sn'].'%');
              }

          })
          ->wherein('complete_state',[1,2,3])
//          ->whereIn('refund_state',[0,2])
//          ->whereIn('appraise_state',[1,2])
            ->commonpage($arr_option);
    }

    /**
     * 通过条件查询所有可自动取消预约的订单
     */
    public function all_auto_cancel_order($arr_select = ['*'],$n_minutes = 30)
    {
        $arr_where = ['appointment_state'=>1, 'pay_state'=>1];
        $s_time = time_to_ymdhis(time() - 60 * $n_minutes);
        return OrderCheckpoint::where($arr_where)->where('created_at','<',$s_time)->select($arr_select)->get();
    }

    /*查询所有7天未评价订单*/
    public function all_auto_appointment_order_waiting_for_apprise($arr_select = ['*'],$n_day = 7){
        $arr_where = [
          'appointment_state'=>2,
          'pay_state'=>2,
          'check_state'=>2,
          'appraise_state'=>1,
        ];

        $s_time = time_to_ymdhis(time() - 60 * 60 * 24 * $n_day);
        return OrderCheckpoint::where($arr_where)->whereIn('refund_state',[0,2])->where('updated_at','<',$s_time)->select($arr_select)->get();
    }

    /*评价所有7天未评价订单*/
    public function apprise_all_waiting_appointment_order($n_day = 7){
//        $arr_where = [
//          'appointment_state'=>2,
//          'pay_state'=>2,
//          'check_state'=>2,
//          'appraise_state'=>1,
//        ];

        $arr_where = [
          'complete_state'=>1,
          'is_finish'=>1,
          'appraise_state'=>1,
        ];

        $s_time = time_to_ymdhis(time() - 60 * 60 * 24 * $n_day);
        $arr_data = ['appraise_state'=>2];
        return OrderCheckpoint::where($arr_where)->where('updated_at','<',$s_time)->update($arr_data);
    }


    /**
     * 根据order_checkpoint_vehicle_id查询主表数据
     *
     * @param int   $n_order_checkpoint_vehicle_id
     * @param array $arr_select
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one_by_vehicle_id($n_order_checkpoint_vehicle_id = 0, $arr_select = ['*'])
    {
        return OrderCheckpoint::where(
          function ($query)
          use ($n_order_checkpoint_vehicle_id) {
              $n_order_checkpoint_vehicle_id = intval($n_order_checkpoint_vehicle_id);
              if ($n_order_checkpoint_vehicle_id > 0) {
                  $query->whereHas('check_vehicle',
                    function ($query)
                    use ($n_order_checkpoint_vehicle_id) {
                        $query->where('id', $n_order_checkpoint_vehicle_id);
                    });

              }
          }
        )
                              ->select($arr_select)
                              ->first();

    }

    /**
     *  根据条件获取数量（开发票时检测当前订单是否可以开票）
     *  hinq 2020 6 15
     *
     **/
    public function get_count_whereIn( array $arr_whereIn = ['key'=>'id','value'=>[]]){
        return OrderCheckpoint::whereIn($arr_whereIn['key'], $arr_whereIn['value'])->whereIn('is_invoice',[1,2])->count();
    }

}